import React from 'react';
import { inject, observer } from 'mobx-react';
import { toJS, observe } from 'mobx';
import { Bubble , Button , List , Icon , Checkbox , Radio , Select , InputItem} from 'weaver-mobile';
import { Form } from 'weaver-mobile-page';
import { withRouter, Route, Link } from 'react-router-dom';
import { getLabel } from '../../util/common';
import * as ForwardPage from '../../util/forwardPage';

const AgreeItem = Checkbox.AgreeItem;
const CheckboxItem = Checkbox.CheckboxItem;
const RadioItem = Radio.RadioItem;

@inject('freeFlowSetStore')
@withRouter
@observer
export default class WfFreeDetailSet extends React.Component{
    componentDidMount() {
        const { location = {} , freeFlowSetStore} = this.props;
        const { setCurrentElement , initDatas , formStore} = freeFlowSetStore;
        const { currentGroup = {} ,parentGroup={}, detailType='' , condition=[] , pcPublicFreeStore} = location;

        initDatas({currentElement:currentGroup,parentElement:parentGroup,detailType,pcPublicFreeStore});

        /**初始化form */
        if(detailType == 'editNode'){
            let {
                allowComments = false, allowModify = '0', allowForward = false, allowTransfer = false, earlyReminder = -1, groupid = 0, loopReminder = false,
                loopRemind = '', remindInterval = '', mustPass = false, nextNodeEditPurview = '2', nodename = '', nodetype = '1', overflowtime = '', overflowtimetype = '0', operators,
                reminderInterval = -1, advanceRemind = '', overflowtimehour = '', overflowtimeminute = '', overflowtimedate = '', overflowtimetime = '', signType = '',
                operatorReplaceDatas = [], isrejectremind = '0', ischangrejectnode = '0', isselectrejectnode = '1', isSubmitDirectNode = '0'
            } = currentGroup.nodeEntity;
            
            if(condition && condition.length > 0){
                condition[0].items[3].browserConditionParam.valueArray = operatorReplaceDatas;
            }
            formStore.initForm(condition,'/req/wfFreeFlowSet/detail');

            const operatorObj = operatorReplaceDatas;
            const operatorDatas = [];
            operatorObj.map(v => {
                operatorDatas.push({id:v.id,name:v.name,type:v.type});
            });
            let updataObj = {
                nodename:{value:nodename},
                nodetype:{value: nodetype + ''},
                allowModify:{value:(allowModify === true || allowModify == '1') ? '1' : '0'} ,
                allowForward:{value:(allowForward === true || allowForward == '1') ? '1' : '0'} ,
                allowTransfer:{value:(allowTransfer === true || allowTransfer == '1') ? '1' : '0'} ,
                allowComments:{value:(allowComments === true || allowComments == '1') ? '1' : '0'} ,
                nextNodeEditPurview:{value:nextNodeEditPurview},//RADIO
                syncAllNode: {value:-1},//checkbox
                overflowtimetype:{value:overflowtimetype + ''} ,
                overflowtimehour:{value:overflowtimehour},
                overflowtimeminute:{value:overflowtimeminute+''} ,
                overflowtimedate:{value:overflowtimedate},
                overflowtimetime:{value:overflowtimetime},
                advanceRemind:{value:advanceRemind + ''} ,
                earlyReminder:{value:earlyReminder},
                loopRemind:{value:loopRemind + ''} ,
                remindInterval:{value:remindInterval + ''} ,
                loopReminder:{value:loopReminder + ''} ,
                loopReminderTime:{value: -1},//SELECT,
                signType:{value: signType + ''},
                operators: {value: operatorDatas}
            };
            formStore.updateFields(updataObj);
        }
        /****/
        document.title = "自由流程详细设置";
    }
    render(){
        const { freeFlowSetStore } = this.props;
        const { currentDatas = {}} = freeFlowSetStore;
        const { detailType = '' , currentElement={}} = currentDatas;
        console.log(detailType,'detailType',currentElement);
        /**
            detailType : node-节点属性 || time-超时时间 || branch-分支属性
         */
        let detailTitle = '自由流程详细设置';
        if(detailType == 'editNode'){
            detailTitle = '节点属性';
        }else if(detailType == 'sign'){
            detailTitle = '加签属性';
        }else if(detailType == 'branch'){
            detailTitle = '分支属性';
        }

        return (
            <div className='free-flow-set freeFlowSet-detail'>
                <div className='flow-set-header'>{detailTitle}</div>
                <div className='flow-set-content'>{this.getContent()}</div>
                <div className='flow-set-bottom'>
                    {this.getBottoms()}
                </div>
            </div>
        )
    }
    getContent = () => {
        const { freeFlowSetStore } = this.props;
        const { currentDatas = {} , formStore} = freeFlowSetStore;
        const { detailType = '' , currentElement={}} = currentDatas;

        let content = [];
        
        if(detailType == 'branch'){
            content.push(this.getRenderBranch());
        }else if(detailType == 'editNode'){
            content.push(this.getCusFields());
        }else{
            content.push(this.getRenderSignFields());
        }
        return (
            <div className='content'>{content}</div>
        )
    }
    /** 加签属性 */
    getRenderSignFields = () => {
        const signOptions = [
            {
                key: "1",
                selected: true,
                showname: "回到本节点"
            },{
                key: "2",
                selected: false,
                showname: '自动转入下一节点 '
            }
        ];
        let result = [];
        result.push(<Select
            value={'1'}
            active = {true}
            label={'加签类型'}
            options={signOptions}
            onChange={(v)=>{
                // freeFlowSetStore.currentDatas = {...freeFlowSetStore.currentDatas,currentElement:{...currentElement,mergeValue:value,mergeType:v}}
                // setBranchType(v);
            }}
        />)
        return <div className="sign-attr">{result}</div>;
    }
    /** 自定义渲染 form */
    getCusFields = () => {
        const { freeFlowSetStore } = this.props;
        const { formStore , formPanelToggleState} = freeFlowSetStore;
        const { conditioninfo, isInit } = formStore;
        console.log('conditioninfo: ', toJS(conditioninfo));
        let res = []
        if (isInit) {
            conditioninfo.forEach((group,index) => {
                const fields = this.getFormItemFields(group.items);
                res.push(
                    <div className={`wm-form-group`} key={group.title}>
                        {group.title && 
                            <div className={`wm-form-title`} onClick={() => this.handleToggle(index)}>
                                {group.title}
                                <Icon type={formPanelToggleState[index] ? 'up' : 'down'} />
                            </div>
                        }
                        <div className={`wm-form-list-wrap ${formPanelToggleState[index] ? 'show' : 'hide'}`}>
                        <List>
                            {fields}
                        </List>
                        </div>
                    </div>
                )
            });
        }
        return res;
    }
    /** 自定义渲染form item 节点属性*/
    getFormItemFields = (items=[]) => {
        const { freeFlowSetStore } = this.props;
        const { currentDatas = {} ,formStore } = freeFlowSetStore;
        const { detailType = '' , currentElement={} , parentElement={}} = currentDatas;

        const { mergeType = ''} = parentElement;
        const { nodeEntity={} } = currentElement;
        const { operatorReplaceDatas=[]} = nodeEntity;
        const formParams = formStore.formParams;
        const { overflowtimetype = '' , overflowtimedate = '' , overflowtimetime='' , overflowtimehour='' , overflowtimeminute ='' ,
          advanceRemind='',nodetype} = formParams;
        console.log(formParams,'formParams');
        let fields = [];
        items.forEach((field) => {
            const domkey = field.domkey[0];
            if( domkey == 'nextNodeEditPurview'){
                field.active = true;
            }
            let showMustPass = domkey== 'nodename' && mergeType == '3';
            const item = (<div className={`freeFlow-${domkey}${showMustPass?' nodename-showmustPass':''}`}>
                    <Form.Item
                        key={field.domkey.join('__')}
                        form={formStore}
                        fieldConfig={field}
                        onChange={domkey == 'operators' ? (field,datas) => {
                            let _datas = toJS(datas);
                            freeFlowSetStore.currentDatas.currentElement.nodeEntity.operatorReplaceDatas = _datas;
                            formStore.updateFields({operators:{value:_datas}});
                        }: formStore.onChange}
                    />
                    {domkey== 'nodename' && mergeType == '3' && this.getMustPassComs(nodeEntity)}
                    </div>);
            if(domkey == 'overflowtimetype'){
                fields.push(item);
                ['0','1','2'].indexOf(overflowtimetype)<0 && fields.push(this.getOvertimeRender('after'));
            }else if(domkey == 'overflowtimehour' || domkey == 'overflowtimeminute'){
                if(overflowtimetype == '1'){
                    fields.push(item);
                    if(domkey == 'overflowtimeminute'){
                       fields.push(this.getOvertimeRender('after')); 
                    }
                }
            }else if(domkey == 'overflowtimedate'){
                if(overflowtimetype == '2'){
                    field.mode = 'datetime';
                    fields.push(<div className={`freeFlow-${domkey}`}><Form.Item
                        key={field.domkey.join('__')}
                        form={formStore}
                        fieldConfig={field}
                        onChange={formStore.onChange}
                    /></div>);  
                    fields.push(this.getOvertimeRender('after')); 
                }
            }else if(domkey == 'advanceRemind'){
                fields.push(item);
                if(advanceRemind != '0'){
                    fields.push(this.getOvertimeRender('before')); 
                }
            }else{
                if(domkey == 'loopRemind' || domkey == 'remindInterval' || domkey  == 'overflowtimetime'){
                    return;
                }
                if(domkey  == 'allowModify' && (nodetype == '4' || nodetype == '0' || nodetype=='3')){//允许修改表单内容 （查阅类型,创建，归档不显示）
                    return;
                }

                fields.push(item);  
            }
        });
        return fields;
    }
    getOvertimeRender = (type='after') => {
        const { freeFlowSetStore } = this.props;
        const { formStore , formPanelToggleState , currentDatas} = freeFlowSetStore;
        const { detailType = '' , currentElement={}} = currentDatas;
        const { nodeEntity = {}} = currentElement;
        const { overtimeToNextOperator = '0' , afterLoopRemind = '' , beforeLoopRemind = '' , afterRemindInterval = '',
        beforeRemindInterval = ''} = nodeEntity;
        const { conditioninfo, isInit } = formStore;
        let options = conditioninfo[1].items[7].options;
        let overToNextComs = (<AgreeItem 
                                checked = {overtimeToNextOperator == '1'}
                                onChange = {(e)=>{
                                    console.log(e,'vvvvvvv');
                                    let value = e.target.checked ? 1 : 0;
                                    freeFlowSetStore.currentDatas.currentElement.nodeEntity['overtimeToNextOperator'] = value;
                                }}
                            >
                                超时自动流转至下一操作者
                            </AgreeItem>
                        );
        let nodeAfterBeforeComs = (<AgreeItem 
                                checked = {type=='after' ? (afterLoopRemind=='1') : (beforeLoopRemind == '1')}
                                onChange = {(e)=>{
                                    console.log(e,'vvvvvvv');
                                    let value = e.target.checked ? 1 : 0;
                                    let key = type=='after' ? 'afterLoopRemind' : 'beforeLoopRemind';
                                    freeFlowSetStore.currentDatas.currentElement.nodeEntity[key] = value;
                                }}
                                className="node-after-before-check"
                            >
                                {`节点超时${type=='after'?'后':'前'}，每`}
                            </AgreeItem>
                        );
        let select = (<div className="cus-select"><Select
                        value={type=='after' ? afterRemindInterval : beforeRemindInterval}
                        // label={'提醒一次'}
                        viewAttr={3}
                        options={options}
                        onChange={(v)=>{
                            console.log(v,'vvvvvvvvv');
                            let value = v;
                            let key = type=='after' ? 'afterRemindInterval' : 'beforeRemindInterval';
                            freeFlowSetStore.currentDatas.currentElement.nodeEntity[key] = value;
                        }}
            /><span className="select-label">提醒一次</span></div>);
        let res = [];
        if(type=='after'){
            res.push(overToNextComs);
        }
        res.push(nodeAfterBeforeComs);
        res.push(select);
        return <div className="overtime-seting">{res}</div>;
    }
    /*****渲染分支属性*****/
    getRenderBranch = () => {
        const { freeFlowSetStore } = this.props;
        const { branchType , setBranchType , currentDatas} = freeFlowSetStore;
        const { detailType = '' , currentElement={}} = currentDatas;
        const { mergeValue = '1' , mergeType='1' , parallelNodeGroupDatas = []} = currentElement;
        
        const branchOptions = [
            {
                key: "1",
                selected: true,
                showname: "按比例通过"
            },{
                key: "2",
                selected: false,
                showname: '按分支数通过 '
            },{
                key: "3",
                selected: false,
                showname: '指定通过分支'
            }
        ];
        let results = [];
        const _type = branchType == '' ? ''+mergeType : branchType;
        results.push(<Select
            value={_type}
            active = {true}
            label={'通过分支选项'}
            options={branchOptions}
            onChange={(v)=>{
                console.log(v,'vvvvvvvvv');
                const value = v == '1' ? '100' : v == '2' ? '1' : '1';
                freeFlowSetStore.currentDatas = {...freeFlowSetStore.currentDatas,currentElement:{...currentElement,mergeValue:value,mergeType:v}}
                setBranchType(v);
            }}
        />);

        /**detail */
        let detail;
        const mustPassDatas = [
            {value:0,label:'节点名称1'},
            {value:1,label:'节点名称2'},
            {value:2,label:'节点名称3'},
        ];
        //自定义input后的图标
        let inputExtraComs = (<span className="cus-inputItem">
            {_type == 1 && '%'}
            {/* {mergeValue != '' && <span>*</span>} */}
            <Icon type='editor'/>
        </span>)
        if(_type == '1'){
            detail = [];
            detail.push(<InputItem
                value={mergeValue}
                type={'number'}
                placeholder = '请输入'
                extra = {inputExtraComs}
                onChange = {(v)=>{
                    v < 0 ? v = 0 : '';
                    v > 100 ? v = 100 : '';
                    freeFlowSetStore.currentDatas = {...freeFlowSetStore.currentDatas,currentElement:{...currentElement,mergeValue:v}}
                }}
                className="bili-input"
            >
                通过比例
            </InputItem>);
            detail.push(<div className="bili-tips">
                比例=通过分支数/总分支数，实际通过比例大于等于所设比例时，转入下一节点。
            </div>)
        }else if(_type == '2'){
            detail = <InputItem
                value={mergeValue}
                type={'number'}
                placeholder = '请输入'
                extra = {inputExtraComs}
                onChange = {(v)=>{
                    v < 1 ? v = 1 : '';
                    freeFlowSetStore.currentDatas = {...freeFlowSetStore.currentDatas,currentElement:{...currentElement,mergeValue:v}}
                }}
            >
                通过分支数
            </InputItem>
        }else{
            detail = (<div>
                <List renderHeader = {()=> '请至少选择1个必须通过的节点！'}>
                    {parallelNodeGroupDatas.map((v,i)=>(
                        <CheckboxItem key={v.id} checked={v.nodeEntity.mustPass} onChange={(e)=>{
                            const value = e.target.checked;
                            let paralls = parallelNodeGroupDatas;
                            paralls[i].nodeEntity.mustPass = value;
                            freeFlowSetStore.currentDatas = {...freeFlowSetStore.currentDatas,currentElement:{...currentElement,parallelNodeGroupDatas:paralls}}
                        }}>
                            <span className='nodename-icon'><i></i></span>
                            <span>{v.nodeEntity ? v.nodeEntity.nodename : '节点名称'}</span>
                        </CheckboxItem>
                    ))}
                </List>
            </div>)
        }
        results.push(detail);

        return <div className="branch-content">{results}</div>;
    }
    /*****必须通过***/
    getMustPassComs = (nodeEntity) => {
        const { freeFlowSetStore } = this.props;
        const { currentDatas = {} ,formStore } = freeFlowSetStore;
        const { mustPass = false } = nodeEntity;
        let res = <Radio
           name = 'mustpass' 
           checked = {mustPass}
           onChange = {(e)=>{
                let value = e.target.checked;
                freeFlowSetStore.currentDatas.currentElement.nodeEntity.mustPass = value;
                console.log(e,'eeeeeeee');
           }}
        >
        必须通过
        </Radio>

        return res;
    }
    /*********/
    handleToggle = (index) => {
        const { freeFlowSetStore } = this.props;
        const { formStore , formPanelToggleState} = freeFlowSetStore;

        freeFlowSetStore.formPanelToggleState[index] = !formPanelToggleState[index];
    }
    getBottoms = () => {
        const { freeFlowSetStore , history} = this.props;
        const { currentDatas = {} , formStore} = freeFlowSetStore;
        const { detailType = '' , currentElement={} , pcPublicFreeStore} = currentDatas;
        const formParams = formStore.formParams;
        let btns = [];
        btns.push(<Button 
                type="primary" 
                onClick={()=>{
                    let resNodes = currentElement;
                    if(detailType == 'editNode'){
                        const result = formStore.doValidate();
                        if(!result.pass){
                            console.log(result,'------------');
                            return;
                        }
                        const replaceDatas = resNodes.nodeEntity.operatorReplaceDatas || [];
                        let operatorTransType = {// 记录所有操作者type-便于转换
                            "resource": 1,
                            "subcom": 2,
                            "dept": 3,
                            "group": 4,
                            "virtual_subcom": 5,
                            "virtual_dept": 7,
                            "all": 9
                        };
                        let operatorsStr = [] , _repDatas = [];
                        replaceDatas.map(v=>{
                            operatorsStr.push(`${operatorTransType[v.type]}_${v.id}`);
                            _repDatas.push({id:v.id,name:v.name,type:v.type});
                        });
                        formParams['operatorids'] = formParams['operators'];
                        formParams['operators'] = operatorsStr.join(',');
                        resNodes.nodeEntity.operatorReplaceDatas = _repDatas;
                        resNodes.nodeEntity = {...resNodes.nodeEntity,...formParams};
                    }
                    console.log(resNodes,'resNodes')
                    let iframe = window.document.getElementById('mobile-freeFlow').contentWindow;
                    const func = iframe.wfFreeFlowToMobileUtils.reloadFreeNodeDatas;
                    func && func(resNodes,pcPublicFreeStore);
                    history.goBack();
                }}
            >
            保存
        </Button>);
        return btns;
    }
    resetForm = () => {
        const { freeFlowSetStore } = this.props;
        const { formStore} = freeFlowSetStore;
        formStore.resetFields();
    }
    handleSubmit = () => {
        const { freeFlowSetStore } = this.props;
        const { formStore} = freeFlowSetStore;
        const result = formStore.doValidate();
        const formParams = formStore.formParams;
        if(result.pass){
            Bubble.success('验证成功！',1,'50%');
        }
    }
}